﻿namespace OrderManagerSystem {
    public class OrderService {
        List<Order> orderList = new List<Order>();
        public int GetCurOrderCnt() => orderList.Count;
        public void AddOrder(Order order) {
            if (!orderList.Exists(or => or.Equals(order))) {
                orderList.Add(order);
            }
            else {
                Console.WriteLine("Order Exist. Add Failed.");
            }
        }


        public void RemoveOrder(int id) {
            try {
                orderList.Remove(orderList.Find(or => or.id == id));
            }
            catch (ArgumentNullException e) {
                Console.WriteLine("Order Not Found. Remove Failed.");
            }
            catch (Exception e) {
                Console.WriteLine($"{e.Message}");
            }
        }

        public void ChangeOrder(int id, OrderDetails orderDetail) {
            try {
                int index = orderList.IndexOf(orderList.Find(or => or.id == id));
                orderList[index].ChangeDetail(orderDetail);
            }
            catch (ArgumentNullException e) {
                Console.WriteLine("Order Not Found. Change Failed.");
            }
            catch (Exception e) {
                Console.WriteLine($"{e.Message}");
            }
        }

        public Order[] QueryOrder(Func<Order, bool> action) {
            return orderList.Where(action).OrderBy(or => or.TotalMoney).ToArray();
        }

        public Order[] SortOrder(Comparison<Order> cmp) {
            if (cmp == null) {
                cmp = (or1, or2) => or1.id.CompareTo(or2.id);
            }
            orderList.Sort(cmp);
            return orderList.ToArray();
        }
    }
}